#!/usr/bin/env bash

# Copyright Istio Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
set -u
set -o pipefail

# $snippet route_traffic_v1.sh
$ kubectl apply -f @samples/tcp-echo/tcp-echo-all-v1.yaml@ -n istio-io-tcp-traffic-shifting
# $endsnippet

# $snippet check_tcp_echo_is_running.sh
$ export INGRESS_HOST={{ .ingressHostCommand }}
$ export INGRESS_PORT={{ .ingressPortCommand }}
# $snippet

echo "sending traffic to $INGRESS_HOST:$INGRESS_PORT"

# $snippet send_traffic_to_echo_v1.sh
$ for i in {1..20}; do \
docker run -e INGRESS_HOST=$INGRESS_HOST -e INGRESS_PORT=$INGRESS_PORT \
  --rm busybox sh -c "(date; sleep 1) | nc $INGRESS_HOST:$INGRESS_PORT"
done
# $verify verifier="notContains"
two
# $endsnippet

# $snippet deploy_tcp_echo_v2_20_percent_rule.sh 
$ kubectl apply -f @samples/tcp-echo/tcp-echo-20-v2.yaml@ -n istio-io-tcp-traffic-shifting
# $endsnippet

# $snippet confirm_20_percent_rule.sh
$ kubectl get virtualservice tcp-echo -o yaml -n istio-io-tcp-traffic-shifting
# $verify verifier="contains"
spec:
  gateways:
  - tcp-echo-gateway
  hosts:
  - '*'
  tcp:
  - match:
    - port: 31400
    route:
    - destination:
        host: tcp-echo
        port:
          number: 9000
        subset: v1
      weight: 80
    - destination:
        host: tcp-echo
        port:
          number: 9000
        subset: v2
      weight: 20
# $endsnippet

# $snippet more_tcp_traffic_to_echos.sh
$ for i in {1..20}; do \
docker run -e INGRESS_HOST=$INGRESS_HOST -e INGRESS_PORT=$INGRESS_PORT \
  --rm busybox sh -c "(date; sleep 1) | nc $INGRESS_HOST:$INGRESS_PORT"
done
# $verify verifier="contains"
two
# $endsnippet